package com.yanxi.yxregiserve.web.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yanxi.yxregiserve.web.domin.system.ConfigData;
import com.yanxi.yxregiserve.web.service.system.ConfigDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;

import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import java.util.stream.Collectors;

/**
 * 废弃
 * 拉取配置 直接加载数据库配置
 */
public class PullConfigLoader implements EnvironmentPostProcessor {

    @Autowired
    private ConfigDataService configDataService;

    private static final String PROPERTY_SOURCE_NAME = "databaseProperties";

    private static final String SOURCE_TAG = "regiserve";

    /**
     * 获取日志记录器
     */
    private static final Logger logger = Logger.getLogger(PullConfigLoader.class.getName());


    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {

        logger.info("ServerConfig loading start");

        try {

            /**
             * 条件查询 配置 Map
             */
            List<ConfigData> configData = configDataService.selectTList(ConfigData.builder().tag(SOURCE_TAG).build());

            /**
             * 转化为map
             */
            Map<String, Object> configDataMap = configData.stream()
                    .collect(Collectors.toMap(ConfigData::getKey, ConfigData::getValue));

            /**
             * 加载配置
             */
            environment.getPropertySources().addFirst(new MapPropertySource(PROPERTY_SOURCE_NAME, configDataMap));

            logger.info("ServerConfig loading Success");


        } catch (Exception e) {

            e.printStackTrace();

            logger.info("ServerConfig loading Exception");

        }

    }
}
